package myservice.android.activities;

import java.util.ArrayList;

import myservice.android.Global;
import myservice.android.R;
import myservice.android.database.Database;
import myservice.android.utilities.PopupMenu;
import myservice.android.utilities.Record;
import myservice.android.utilities.RecordAdapter;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class PersonListActivity extends BaseActivity {
	
	private Button addPersonButton;
	private ArrayList<Record> recordData;
	private ListView recordList;
	private TextView noPersonsDefinedText;
	private RecordAdapter recordAdapter;

	private int mode; // 0 = modify interested ones; 1 = pick a person from the list
	
	@Override
	protected void initializeLayoutIdAndTitle() {
		
		layoutId = R.layout.person_list;
		
	}

	@Override
	protected void retrieveViews() {

        addPersonButton = (Button) findViewById(R.id.addPersonButton);
        recordList = (ListView) findViewById(R.id.interestedList);
        noPersonsDefinedText = (TextView) findViewById(R.id.noInterestedMessage);
		
	}

	@Override
	protected void loadActivityParameters() {

		mode = activityParameters.getInt("mode");
		
	}

	@Override
	protected void assignListeners() {

        addPersonButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				
				final Dialog dialog = new Dialog(PersonListActivity.this);
				dialog.setContentView(R.layout.add_person_dialog);
				dialog.setTitle(Global.res.getString(R.string.title_add_new_person));
				
				Button saveButton = (Button) dialog.findViewById(R.id.saveButton);				
				Button cancelButton = (Button) dialog.findViewById(R.id.cancelButton);
				final EditText nameField = (EditText) dialog.findViewById(R.id.nameField);
				
				saveButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {					
						Database.execSQL("INSERT INTO persons (personid,name,status,comments,street,houseapartment,townregion,telephone,timestamp) VALUES ("
									     +Database.getUniqueRowId("persons")+",'"+Global.fixText(nameField.getText())+"',1,'','','','','',"+Global.getTimeStamp()+")");	
						dialog.dismiss();
						updateList();
					}			
				});
				
				cancelButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						dialog.dismiss();				
					}			
				});		
				
				dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);								
				dialog.show();								
				
			}
        }); 
		
	}		         
    
	private void updateList() {
		
		PopupMenu.createPopupMenu(this);
		
		recordData = new ArrayList<Record>();
		
		String sql = "SELECT * FROM persons WHERE timestamp<>"+Global.TIMESTAMP_DELETED;
		if (Global.showInactives==false)
			sql = sql + " AND status<>0";
		sql=sql+" ORDER BY name";
    	Cursor cursor = Database.select(sql);
    	
    	boolean noInterestedDefined = true;

    	while (cursor.moveToNext()) {
    		noInterestedDefined=false;
    		Record rec = new Record();
    		rec.id=cursor.getInt(cursor.getColumnIndex("personid"));
    		rec.firstLine=cursor.getString(cursor.getColumnIndex("name"));
    		rec.status=cursor.getInt(cursor.getColumnIndex("status"));
    		rec.secondLine=Global.getFormattedAddress(cursor.getString(cursor.getColumnIndex("houseapartment")), cursor.getString(cursor.getColumnIndex("street")), cursor.getString(cursor.getColumnIndex("townregion")));
    		recordData.add(rec);
    	}	
    	cursor.close();    	 
    	
    	if (noInterestedDefined==true)
    		noPersonsDefinedText.setVisibility(View.VISIBLE);
    	else
    		noPersonsDefinedText.setVisibility(View.GONE);
    	
        recordAdapter = new RecordAdapter(this, R.layout.list_row, recordData, 0);
        recordList.setAdapter(recordAdapter);
        
        recordList.setOnItemLongClickListener(new OnItemLongClickListener () {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				final long personId = recordData.get(position).id;					
				
				PopupMenu.menuHeading.setText(recordData.get(position).firstLine);
				
				PopupMenu.menuOption1.setText(Global.res.getString(R.string.menuitem_modify_person));		
				PopupMenu.menuOption2.setText(Global.res.getString(R.string.menuitem_owned_publications));		
				PopupMenu.menuOption3.setText(Global.res.getString(R.string.menuitem_calls));		
				PopupMenu.menuOption4.setText(Global.res.getString(R.string.menuitem_delete_person));				
				
				PopupMenu.menuOption1.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						PopupMenu.closeMenu();
						modifyPerson(personId);				
					}					
				});
				
				PopupMenu.menuOption2.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						PopupMenu.closeMenu();
						Intent i = new Intent(getApplicationContext(), PublicationListActivity.class);
						i.putExtra("person_id",personId);			
						startActivity(i);			
					}					
				});		
				
				PopupMenu.menuOption3.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						PopupMenu.closeMenu();
						Intent i = new Intent(getApplicationContext(), PersonCallListActivity.class);
						i.putExtra("person_id",personId);			
						startActivity(i);	
					}					
				});		
				
				PopupMenu.menuOption4.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						PopupMenu.closeMenu();
						AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(PersonListActivity.this);
						alertDialogBuilder.setTitle(Global.res.getText(R.string.title_warning));				
						alertDialogBuilder
							.setMessage(Global.res.getText(R.string.message_delete_person_confirmation))
							.setPositiveButton(Global.res.getText(R.string.button_yes),new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int id) {
									Database.deleteInterestedPerson(personId);
									updateList();
								}
							  })
							.setNegativeButton(Global.res.getText(R.string.button_no),new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.cancel();
								}
							});
				 
						AlertDialog alertDialog = alertDialogBuilder.create();
						alertDialog.show();		
					}					
				});					
				
				PopupMenu.showMenu(view);				
				
				return true;
			}
        	
        });
        
        recordList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				
					clickPerson(recordData.get(position).id);

			}
        	
        });
    	
	}
	
	private void modifyPerson(long personId) {
		Intent i = new Intent(getApplicationContext(),PersonActivity.class);
		i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		i.putExtra("person_id",personId);
		startActivity(i);
	}
	
	private void clickPerson(long personId) {
		if (mode==0) {			 
			modifyPerson(personId);
		} else {
			Global.selectedId=personId;
			Global.selectedType=0;
			finish();
		}		
	}

	@Override
	protected void updateUi() {

        if (mode==0)
        	activityTitleView.setText(Global.res.getString(R.string.title_persons));
        else
        	activityTitleView.setText(Global.res.getString(R.string.title_select_person));
        
        updateList();
		
	}
    
    
}